# -*- coding:utf-8 -*-
# !usr/bin/env python
import pdb
import signal

import pexpect
import sys
import os

sys.path.append(os.path.join(sys.path[0], '../..'))
from csi_config import read_setting

wlan = read_setting('wlan')
PASSWD = read_setting('password')

def error(err=0):
    if err == 0:
        print("Error - EOF! -- zz")
    elif err == 1:
        print("Error - TIMEOUT! -- zz")
    sys.exit(-1)

def killchildprocess():
    if childs[0] is not None:
        pid = childs[0].pid
        kill = pexpect.spawn('sudo kill %s' % pid)
        try:
            index = kill.expect('password')
            if index == 0:
                kill.sendline(PASSWD)
        except pexpect.EOF:
            error()
        while kill.isalive():
            pass
        print("Kill Server Process [%d] Successful! -- zz" % pid)

childs = []
try:
    if __name__ == '__main__':
        cmd='%s/csi_log'%os.path.abspath(os.path.dirname(__file__))
        child = pexpect.spawn('sudo %s'%cmd)
        childs.append(child)
        index = child.expect('password')
        if index == 0:
            child.sendline(PASSWD)
            print('pid=%d'%child.pid)
            print("Launch Server Process Successful! -- zz")
            while True:
                try:
                    idx = child.expect(['bind_csi', '.*command not found'])
                    if idx == 0:
                        print("Please wait while system releasing address... -- zz")
                        killchildprocess()
                    elif idx == 1:
                        print('command not found')
                except pexpect.TIMEOUT:
                    pass  # No Error
                except pexpect.EOF:
                    error()

except KeyboardInterrupt:
    killchildprocess()
